import {  Button, Switch, Modal, Form, Input, Select, message } from 'antd';
import { useEffect, useState } from 'react';
import axios from '../../aixos';
import { connect } from 'react-redux'
import Table from '../../components/Table/Table'

const { Option } = Select;



function User(props) {

  const [pageIndex, setPageIndex] = useState(1)
  const [userList, setUserList] = useState([])
  const pageSize = 10
  const [total, setTotal] = useState(0)

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      render: text => <span>{text}</span>,
    },
    {
      title: '角色',
      dataIndex: 'roleType',
      render: (val) => {
        return <>{props.roleType[val]}</>
      }
    },
    {
      title: '状态',
      dataIndex: 'state',
      render: (val, record) => {
        return <Switch checked={val} onChange={() => changeState(record)} />
      }
    },
    // {
    //   title: '操作',
    //   render: (_, record) => (
    //     <Space size="middle">
    //       {/* <Button>编辑</Button> */}
    //       <Button type='danger' onClick={() => deleteUser(record._id)}>删除</Button>
    //     </Space>
    //   ),
    // },
  ];

  useEffect(() => {
    axios.get('/user', {
      pageIndex,
      pageSize
    }).then(res => {
      setUserList(res.data.records)
      setTotal(res.data.total)
    })
  }, [pageIndex])

  const [isModalVisible, setIsModalVisible] = useState(false);

  const changeState = (record) => {
    console.log(record)
    let changeState = record.state === 0 ? 1 : 0
    axios.put('/user/state-edit', {
      id: record._id,
      state: changeState
    }).then(() => {
      setUserList(userList.map(item => {
        if (item._id === record._id) {
          return { ...record, state: changeState }
        }
        return item
      }))
    })
  }

  const showModal = () => {
    form.resetFields()
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const onFinish = (values) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const selectRole = (e) => {
    console.log(e)
  }
  const handleOk = async () => {
    console.log(form)
    const formData = await form.validateFields()
    axios.post('/user', {
      username: formData.username,
      password: formData.password,
      roleType: formData.roleType,
      state: formData.state || 1,
    }).then(res => {
      setIsModalVisible(false)
      setUserList([res.data, ...userList])
      message.success(res.message)
    })
  };
  const changePage = (index) => {
    console.log(index)
    setPageIndex(index)
  }
  const deleteUser = (id) => {
    axios.delete('/user', {
      id
    }).then(() => {
      setUserList(userList.filter((item) => {
        return item._id !== id
      }))
      setTotal(total - 1)
    })
  }
  const [form] = Form.useForm();
  return (
    <>
      <Table columns={columns} rowKey='_id' dataSource={userList} pagination={{
        current: pageIndex,
        pageSize: pageSize,
        total: total,
        showTotal: () => `共 ${total} 个用户`,
        onChange: changePage
      }}
      action={{
        delete: {callback: deleteUser}
      }}
      >
        <Button type='primary' onClick={showModal}>添加用户</Button>
      </Table>
      <Modal title="添加用户" cancelText='取消' okText='确认'
        visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="角色"
            name="roleType"
            rules={[
              {
                required: true,
                message: '请选择角色',
              },
            ]}
          >
            <Select style={{ width: 120 }} onChange={selectRole} placeholder='请选择角色'>
              {
                Object.keys(props.roleType).map((key) => {
                  return <Option value={key} key={key}>{props.roleType[key]}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item
            label="状态"
            name="state"
            rules={[
              {
                required: false,
                message: '请选择状态',
              },
            ]}
          >
            <Select defaultValue={props.userState[1]} style={{ width: 120 }} onChange={selectRole}
               placeholder='请选择状态'
            >
              {
                Object.keys(props.userState).map((key) => {
                  return <Option value={key} key={key}>{props.userState[key]}</Option>
                })
              }
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default connect((state) => {
  return {
    roleType: state.state.roleType,
    userState: state.state.userState
  }
})(User);